package com.amazon.shop.controller;


import com.amazon.shop.aop.SystemLog;
import com.amazon.shop.constant.ReturnConstant;
import com.amazon.shop.entity.Salesman;
import com.amazon.shop.entity.auth.Roles;
import com.amazon.shop.entity.auth.RolesPermissions;
import com.amazon.shop.entity.auth.Users;
import com.amazon.shop.entity.auth.UsersRoles;
import com.amazon.shop.exception.CustomException;
import com.amazon.shop.service.RolesPermissionsService;
import com.amazon.shop.service.RolesService;
import com.amazon.shop.service.SalesmanService;
import com.amazon.shop.service.UsersRolesService;
import com.amazon.shop.service.impl.PermissionsServiceImpl;
import com.amazon.shop.service.impl.UsersServiceImpl;
import com.amazon.shop.utils.CommonResult;
import com.amazon.shop.vo.SalesmanSaveVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 郭非
 * @since 2021-06-18
 */
@RestController
@RequestMapping("/shop/salesman")
@Api(tags = "业务员站点模块")
public class SalesmanController {
    @Resource
    private SalesmanService salesmanService;
    @Resource
    private UsersServiceImpl usersService;
    @Resource
    private PermissionsServiceImpl permissionsService;
    @Resource
    private RolesService rolesService;
    @Resource
    private UsersRolesService usersRolesService;
    @Resource
    private RolesPermissionsService rolesPermissionsService;

    /**
     * 获取业务员站点列表
     *
     * @return
     */
    @GetMapping("/getSalesmanList")
    @ApiOperation(value = "获取业务员站点列表")
    public CommonResult getSalesmanList(String token) {
        boolean flag = permissionsService.getPermissionList(token, "1");
        if (flag) {
            List<Salesman> salesmanList = salesmanService.list();
            if (salesmanList.size() > 0) {
                List<String> collect = salesmanList.stream().map((salesman) -> {
                    String websiteNumber = salesman.getWebsiteNumber();
                    return websiteNumber;
                }).collect(Collectors.toList());

                return CommonResult.success("获取业务员列表成功").put("salesmanList", collect);
            } else {
                return CommonResult.success("获取业务员列表失败");
            }
        } else {
            throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                    , ReturnConstant.NO_PERMISSION_MESSAGE);
        }
    }

    /**
     * 添加业务员站点
     *
     * @param salesmanSaveVo
     * @return
     */
    @SystemLog(value = "添加业务员站点")
    @PostMapping("/saveSalesman")
    @Transactional
    @ApiOperation(value = "添加业务员站点")
    public CommonResult saveSalesman(@RequestBody SalesmanSaveVo salesmanSaveVo, String token) {
        boolean flag = permissionsService.getPermissionList(token, "2");
        if (flag) {
            //生成自定义用户编号
            String replace = UUID.randomUUID().toString().replace("-", "");
            String userId = replace + "user";

            //处理用户角色信息
            String role = salesmanSaveVo.getRole();
            String company = salesmanSaveVo.getCompany();
            QueryWrapper<Roles> rolesQueryWrapper = new QueryWrapper<>();
            rolesQueryWrapper.and((wrapper) -> {
                wrapper.eq("role_name", role);
                wrapper.eq("apartment_name", company);
            });
            Roles roles = rolesService.getOne(rolesQueryWrapper);
            String roleId = roles.getRoleId();
            UsersRoles usersRoles = new UsersRoles();
            usersRoles.setRoleId(roleId);
            usersRoles.setUserId(userId);
            usersRolesService.save(usersRoles);

            //处理角色权限信息
            List<String> permissionList = salesmanSaveVo.getPermissionList();
            List<RolesPermissions> rolesPermissionsList = permissionList.stream().map((permission) -> {
                RolesPermissions rolesPermissions = new RolesPermissions();
                rolesPermissions.setPermissionId(permission);
                rolesPermissions.setRoleId(roleId);
                return rolesPermissions;
            }).collect(Collectors.toList());
            rolesPermissionsService.saveOrUpdateBatch(rolesPermissionsList);

            //处理用户信息
            String userName = salesmanSaveVo.getUserName();
            String password = salesmanSaveVo.getPassword();
            String qq = salesmanSaveVo.getQq();
            String email = salesmanSaveVo.getEmail();
            String phone = salesmanSaveVo.getPhone();
            String name = salesmanSaveVo.getName();
            Users users = new Users();
            users.setRealName(name);
            users.setUserId(userId);
            users.setUserName(userName);
            users.setPassword(password);
            users.setQq(qq);
            users.setEmail(email);
            users.setPhone(phone);
            usersService.save(users);

            String userRealName = usersService.getUserRealName(token);
            return CommonResult.success("添加成功")
                    .put("list", userId)
                    .put("salesman", userRealName);
        } else {
            throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                    , ReturnConstant.NO_PERMISSION_MESSAGE);
        }
    }

    /**
     * 删除业务员站点信息
     *
     * @param id
     * @param token
     * @return
     */
    @SystemLog(value = "删除业务员站点信息")
    @PostMapping("/removeSalesman")
    @ApiOperation(value = "删除业务员站点信息")
    @Transactional
    public CommonResult removeSalesman(String id, String token) {
        boolean flag = permissionsService.getPermissionList(token, "2");
        if (flag) {
            //根据id删除业务员信息
            boolean remove = usersService.removeById(id);
            if (remove) {
                //根据token查询业务员信息
                String userRealName = usersService.getUserRealName(token);
                return CommonResult.success("删除业务员成功")
                        .put("list", id)
                        .put("salesman", userRealName);
            } else {
                return CommonResult.error("删除业务员失败");
            }
        }
        throw new CustomException(ReturnConstant.NO_PERMISSION_CODE
                , ReturnConstant.NO_PERMISSION_MESSAGE);
    }
}

